package com.apigen.platform.util;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT工具类
 *
 * @author API Generator Platform
 * @since 2025-09-24
 */
@Slf4j
@Component
public class JwtUtil {

    @Value("${security.jwt.secret}")
    private String secret;

    @Value("${security.jwt.expiration:7200}")
    private Long expiration;

    @Value("${security.jwt.refresh-expiration:604800}")
    private Long refreshExpiration;

    private static final String CLAIM_USER_ID = "userId";
    private static final String CLAIM_ACCOUNT_NAME = "accountName";
    private static final String CLAIM_IS_ADMIN = "isAdmin";
    private static final String CLAIM_TOKEN_TYPE = "tokenType";
    
    private static final String TOKEN_TYPE_ACCESS = "access";
    private static final String TOKEN_TYPE_REFRESH = "refresh";

    /**
     * 获取密钥
     */
    private SecretKey getSecretKey() {
        return Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 生成访问令牌
     */
    public String generateAccessToken(Long userId, String accountName, Boolean isAdmin) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_USER_ID, userId);
        claims.put(CLAIM_ACCOUNT_NAME, accountName);
        claims.put(CLAIM_IS_ADMIN, isAdmin);
        claims.put(CLAIM_TOKEN_TYPE, TOKEN_TYPE_ACCESS);
        
        return createToken(claims, accountName, expiration * 1000);
    }

    /**
     * 生成刷新令牌
     */
    public String generateRefreshToken(Long userId, String accountName) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_USER_ID, userId);
        claims.put(CLAIM_ACCOUNT_NAME, accountName);
        claims.put(CLAIM_TOKEN_TYPE, TOKEN_TYPE_REFRESH);
        
        return createToken(claims, accountName, refreshExpiration * 1000);
    }

    /**
     * 创建Token
     */
    private String createToken(Map<String, Object> claims, String subject, Long expiration) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + expiration);

        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(now)
                .setExpiration(expiryDate)
                .signWith(getSecretKey(), SignatureAlgorithm.HS256)
                .compact();
    }

    /**
     * 从Token中获取用户ID
     */
    public Long getUserIdFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims != null ? claims.get(CLAIM_USER_ID, Long.class) : null;
    }

    /**
     * 从Token中获取账户名
     */
    public String getAccountNameFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims != null ? claims.getSubject() : null;
    }

    /**
     * 从Token中获取是否管理员
     */
    public Boolean getIsAdminFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims != null ? claims.get(CLAIM_IS_ADMIN, Boolean.class) : false;
    }

    /**
     * 获取Token过期时间
     */
    public Date getExpirationDateFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims != null ? claims.getExpiration() : null;
    }

    /**
     * 从Token中获取Claims
     */
    private Claims getClaimsFromToken(String token) {
        try {
            return Jwts.parserBuilder()
                    .setSigningKey(getSecretKey())
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
        } catch (JwtException e) {
            log.warn("解析JWT Token失败: {}", e.getMessage());
            return null;
        }
    }

    /**
     * 验证Token是否有效
     */
    public boolean validateToken(String token) {
        try {
            Claims claims = getClaimsFromToken(token);
            if (claims == null) {
                return false;
            }
            
            // 检查是否为访问令牌
            String tokenType = claims.get(CLAIM_TOKEN_TYPE, String.class);
            if (!TOKEN_TYPE_ACCESS.equals(tokenType)) {
                return false;
            }
            
            // 检查是否过期
            return !isTokenExpired(claims);
        } catch (Exception e) {
            log.warn("验证JWT Token失败: {}", e.getMessage());
            return false;
        }
    }

    /**
     * 验证刷新令牌是否有效
     */
    public boolean validateRefreshToken(String token) {
        try {
            Claims claims = getClaimsFromToken(token);
            if (claims == null) {
                return false;
            }
            
            // 检查是否为刷新令牌
            String tokenType = claims.get(CLAIM_TOKEN_TYPE, String.class);
            if (!TOKEN_TYPE_REFRESH.equals(tokenType)) {
                return false;
            }
            
            // 检查是否过期
            return !isTokenExpired(claims);
        } catch (Exception e) {
            log.warn("验证JWT刷新Token失败: {}", e.getMessage());
            return false;
        }
    }

    /**
     * 检查Token是否过期
     */
    private boolean isTokenExpired(Claims claims) {
        Date expiration = claims.getExpiration();
        return expiration.before(new Date());
    }

    /**
     * 获取Token剩余有效时间（秒）
     */
    public long getTokenRemainingTime(String token) {
        Date expiration = getExpirationDateFromToken(token);
        if (expiration == null) {
            return 0;
        }
        long remaining = (expiration.getTime() - System.currentTimeMillis()) / 1000;
        return Math.max(remaining, 0);
    }
}











